package com.ljkj.cordial.chat.fragment;


import android.content.Intent;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lanjiu.lib.imclient.bus.EventConstants;
import com.lanjiu.lib.imclient.bus.MessageEvent;
import com.lanjiu.lib.imclient.ims.IMSClientHelper;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.activity.LoginActivity;
import com.ljkj.cordial.chat.activity.PersonalActivity;
import com.ljkj.cordial.chat.activity.SysSettingActivity;
import com.ljkj.cordial.chat.activity.ToggleAccountActivity;
import com.ljkj.cordial.chat.base.BaseFragment;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.dao.DbController;
import com.ljkj.cordial.chat.dao.UserTableBean;
import com.ljkj.cordial.chat.notify.AppBadgerManager;
import com.ljkj.cordial.chat.notify.NotificationUtils;
import com.ljkj.cordial.chat.util.AlbumManageUtil;
import com.ljkj.cordial.chat.util.DeleteHistoryUtil;
import com.ljkj.cordial.chat.util.ObserverThread;
import com.ljkj.cordial.lengthtcpheartbeat.TcpLengthHeartbeatBroadcastReceive;
import com.nic.view.util.glide.GlideUtil;
import com.nic.view.widget.CircleImageView;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class NavMeFragment extends BaseFragment {


    @BindView(R.id.iv_user)
    CircleImageView ivUser;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_id)
    TextView tvId;
    @BindView(R.id.ll_user_info)
    LinearLayout llUserInfo;
    @BindView(R.id.ll_sw_account)
    LinearLayout llSwAccount;
    @BindView(R.id.ll_sys_setting)
    LinearLayout llSysSetting;
    @BindView(R.id.tv_quit)
    TextView tvQuit;
    @BindView(R.id.iv_is_visitor)
    ImageView ivIsVisitor;

    Unbinder unbinder;
    private String mPath;
    private OnQuitListener mOnQuitListener;

    public static NavMeFragment newInstance(OnQuitListener listener) {
//        Bundle args = new Bundle();
        NavMeFragment fragment = new NavMeFragment();
//        fragment.setArguments(args);
        fragment.setOnQuitListener(listener);
        return fragment;
    }

    public NavMeFragment() {
        // Required empty public constructor
    }


    @Override
    public int getContentLayoutId() {
        return R.layout.fragment_nav_me;
    }

    @Override
    public void initView(View rootView) {
        unbinder = ButterKnife.bind(this, rootView);
//        ivUser.setImageBitmap(EmojiPackage.getBitmapFromAssets(activity, "icon_emoji04.png"));
    }

    private void getUserInfo() {
        UserTableBean u = UserTableBean.getCurrentUser();
        if (u != null) {
            tvName.setText(u.getNickname());
            tvId.setText("ID:" + ChatApp.getInstance().getUserId());
            if (!ChatApp.getInstance().isRegister()) {
                ivIsVisitor.setVisibility(View.VISIBLE);
            }
//            if (!TextUtils.isEmpty(u.getAvatarId())) {
//                AlbumTableBean bean = AlbumTableBean.queryById(Long.valueOf(u.getAvatarId()));
//                if (bean != null && !TextUtils.isEmpty(bean.getMPath())) {
//                    mPath = bean.getMPath();
//                    GlideUtil.getInstance().load(mPath, ivUser);
//                }
//            } else {
//                AlbumManageUtil.getInstance().downLoadFileFriend(u.getAvatar(), u.getUserId(), ivUser);
//            }
//            ImageLoader.getInstance().displayUserAvatar(u.getAvatar(), ivUser);
            if (!TextUtils.isEmpty(u.getAvatar())) {
                if (!TextUtils.isEmpty(u.getAvatar())) {
                    AlbumManageUtil.getInstance().downLoadFileFriendAvatar(u.getAvatar(), u.getUserId(), new AlbumManageUtil.OnFileResponse() {
                        @Override
                        public void onResult(String url, String fileId) {
                            if (!TextUtils.isEmpty(fileId)) {
                                GlideUtil.getInstance().load(fileId, ivUser);
                                u.setAvatarPath(fileId);
                                UserTableBean.update(u);
                            }

                        }
                    });
                }
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getUserInfo();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.iv_user, R.id.ll_user_info, R.id.ll_sw_account, R.id.ll_sys_setting, R.id.tv_quit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_user:
                if (!TextUtils.isEmpty(mPath)) {
                    AlbumManageUtil
                            .getInstance().lookLargePhoto(getActivity(), mPath);
                } else {
                    ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<UserTableBean>() {
                        @Override
                        public void onAction(UserTableBean u) {
                            if (u != null && !TextUtils.isEmpty(u.getAvatar())) {
                                AlbumManageUtil.getInstance().downLoadFileFriendAvatar(u.getAvatar(), u.getUserId(), new AlbumManageUtil.OnFileResponse() {
                                    @Override
                                    public void onResult(String url, String mPath) {
                                        AlbumManageUtil
                                                .getInstance().lookLargePhoto(getActivity(), mPath);
                                    }
                                });
                            }


                        }

                        @Override
                        public UserTableBean onThreadAction() {
                            return UserTableBean.getCurrentUser();
                        }
                    });
                }
                break;
            case R.id.ll_user_info:
                startActivity(new Intent(activity, PersonalActivity.class));
                ChatApp.getInstance().inActivityAnim(activity);
                break;
            case R.id.ll_sw_account:
                startActivity(new Intent(activity, ToggleAccountActivity.class));
                ChatApp.getInstance().inActivityAnim(activity);
                break;
            case R.id.ll_sys_setting:
                startActivity(new Intent(activity, SysSettingActivity.class));
                ChatApp.getInstance().inActivityAnim(activity);
                break;
            case R.id.tv_quit:
                if (null != mOnQuitListener) {
                    mOnQuitListener.beforeQuitDoLogout();
                    new Handler().postDelayed(this::doQuit, 1000);
                } else {
                    doQuit();
                }
                break;
        }
    }


    public interface OnQuitListener {
        void beforeQuitDoLogout();
    }

    private void setOnQuitListener(OnQuitListener mOnQuitListener) {
        this.mOnQuitListener = mOnQuitListener;
    }

    public void doQuit() {
        NotificationUtils.clearNotify(getActivity());
        AppBadgerManager.clean(getActivity());
        TcpLengthHeartbeatBroadcastReceive.loginOut();
//        DeleteHistoryUtil.getInstance().deleteVisitorAll(() -> DeleteHistoryUtil.getInstance().deleteVisitorAll(() -> {
//            IMSClientHelper.getInstance().close();
//            DbController.getInstance().clear();
//            ChatApp.getInstance().setExitFlag(true);
//            ChatApp.getInstance().remove();
//            LoginActivity.jumpTo(getActivity(), Canstants.STATE_REGISTER_LOGIN);
//            activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
//            ChatApp.getInstance().quitApp();
//        });

        DeleteHistoryUtil.getInstance().clear(getActivity(), (clearCyc, isClear) -> {
            EventBus.getDefault().post(MessageEvent.createUiRefreshWidthData(EventConstants.Action.ON_DELETE_HISTORY, "-"));
            IMSClientHelper.getInstance().close();
            DbController.getInstance().clear();
            ChatApp.getInstance().setExitFlag(true);
            ChatApp.getInstance().remove();
            ChatApp.getInstance().quitApp();
            LoginActivity.jumpTo(getActivity(), Canstants.STATE_REGISTER_LOGIN);
            activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
        });
    }
}
